<?php

namespace App\Http\Controllers\App;

use App\Model\PushMsg;
use App\Model\SystemMsg;
use App\Model\UserInterested;
use App\Model\UserMsg;
use App\Model\UserPopularity;
use App\Model\UserTemplate;
use Carbon\Carbon;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use App\Http\Controllers\Controller;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Redis;

class MessageController extends Controller
{
	/**
	 * @var User
	 */
	private $user;

	public function __construct()
	{
		$this->user = Auth::user();
	}

	//人气列表
	public function popularity()
	{
		UserPopularity::whereTargetUserId($this->user->id)->update(['status' => 1]);
		//今日人气
		$today = UserPopularity::where('created_at', '>', Carbon::now()->toDateString())
			->where('target_user_id', '=', $this->user->id)
			->count();
		//总人气
//		$all = UserPopularity::where('target_user_id', '=', $this->user->id)->count();
        $all = UserTemplate::where('user_id', $this->user->id)->value('popularity');
		$subquery = DB::table('user_popularity as up')
			->select(['up.*', 'ud.wechat_name', 'ud.head_portrait','cr.head_picture','cr.user_name'])
			->leftJoin('user_detail as ud', 'ud.user_id', '=', 'up.user_id')
			->leftJoin('cards as cr','up.user_id','=','cr.user_id')
			->where('up.target_user_id', '=', $this->user->id)
			->orderBy('up.created_at', 'DESC')
			->offset(0)->limit(PHP_INT_MAX);
		$bindings = $subquery->getBindings();
		$sql = str_replace('?', '%s', $subquery->toSql());
		$sql = sprintf($sql, ...$bindings);
		$list = DB::table(DB::raw("({$sql}) as tmp"))->groupBy('group_flag')->orderBy('created_at', 'DESC')->paginate(request('limit', 10));

		return $this->renderJson(compact('today', 'all', 'list'));

	}

	//感兴趣列表
	public function interested()
	{
		if ($this->user->is_vip($this->user->id) === false) {
			return $this->fail("开通会员可查看");
		}

		$all = UserInterested::where('target_user_id', '=', $this->user->id)->count();

		$list = DB::table('user_interested as ui')->where('target_user_id', '=', $this->user->id)
			->select(['ui.*', 'ud.wechat_name', 'ud.head_portrait','cr.head_picture','cr.user_name'])
			->leftJoin('user_detail as ud', 'ud.user_id', '=', 'ui.user_id')
			->leftJoin('cards as cr',function($join){
			    $join->on('ui.user_id','=','cr.user_id')->where('ui.user_id', '!=', '');
            })
			->orderBy('ui.created_at', 'DESC')
			->paginate(request('limit', 10));

		return $this->renderJson(compact('all', 'list'));
	}

	//添加感兴趣
	public function addInterested(Request $request)
	{
		$this->validate($request, [
			'target' => 'required',
			'phone' => [
				'regex:/^1[345789][0-9]{9}$/'
			],
		], [
			'target.required' => 'target不能为空',
			'phone.regex' => '手机格式不正确',
		]);

		UserInterested::add($request->input('target'), $request->input('name'), $request->input('phone'));

		return $this->success();
	}

	public function cachePushMsg(Request $request)
	{
		$this->validate($request, [
			'msg_id' => 'required',
		], [
			'msg_id.required' => 'msg_id不能为空',
		]);
		$key = sprintf("pg-%s-%s", $this->user->id, $request->input('msg_id'));

		$redis = Redis::connection();

		$redis->setex($key, 3600 * 24 * 30, 1);

		return $this->success();

	}

	public function isPgCached(Request $request)
	{
		$this->validate($request, [
			'msg_id' => 'required',
		], [
			'msg_id.required' => 'msg_id不能为空',
		]);
		$key = sprintf("pg-%s-%s", $this->user->id, $request->input('msg_id'));

		$redis = Redis::connection();

		return $this->success(['is_cached'=>$redis->get($key) == 1 ? true:false]);
	}

	//获取推送消息
	public function getPushMsg(Request $request)
	{
		$pm = PushMsg::where('status', '=', 1)->orderBy('created_at', 'DESC');
		//指定类型
		if ($request->input('type')) {
			$pm = $pm->where('type', '=', $request->input('type'));
		}
		//指定id
		if ($request->input('id')) {
			$pm = $pm->where('id', '=', $request->input('id'));
		}

		return $this->renderJson(['list' => $pm->paginate(request('limit', 10))]);
	}

	//获取小脉宝消息
	public function getSysMsg(Request $request)
	{
		$sm = SystemMsg::where('to_user_id', '=', $this->user->id)->orderBy('created_at', 'DESC');
		//指定id
		if ($request->input('id')) {
			$sm = $sm->where('id', '=', $request->input('id'));
		}

		$pop = UserPopularity::where('target_user_id', '=', $this->user->id)->where('status', '=', 0)->count();

		$pop_flag = false;
		if ($pop > 0) {
			$pop_flag = true;
		}

		return $this->renderJson(['pop_flag' => $pop_flag, 'list' => $sm->paginate(request('limit', 10))]);
	}

	//用户发的消息分组列表
	public function getUserMsgGroup()
	{
		$subquery = DB::table('user_msg as um')
			->select(['um.*', 'ud.wechat_name', 'ud.head_portrait','cr.head_picture','cr.user_name'])
			->leftJoin('user_detail as ud', 'ud.user_id', '=', 'um.from_user_id')
			->leftJoin('cards as cr','um.from_user_id','=','cr.user_id')
			->where('um.to_user_id', '=', $this->user->id)
			->orderBy('um.created_at', 'DESC')
			->offset(0)->limit(PHP_INT_MAX);
		$bindings = $subquery->getBindings();
		$sql = str_replace('?', '%s', $subquery->toSql());
		$sql = sprintf($sql, ...$bindings);
		$user = DB::table(DB::raw("({$sql}) as tmp"))->groupBy('from_user_id')->orderBy('created_at', 'DESC')->paginate(request('limit', 10));

		return $this->renderJson(['list' => $user]);
	}

	//某个用户发的消息列表
	public function getUserMsg(Request $request)
	{
		$this->validate($request, [
			'from_user_id' => 'required',
		], [
			'from_user_id.required' => 'from_user_id不能为空',
		]);

		$um = UserMsg::where('to_user_id', '=', $this->user->id)
			->where('from_user_id', $request->input('from_user_id'))
			->orderBy('created_at', 'DESC');

		//指定id
		if ($request->input('id')) {
			$um = $um->where('id', '=', $request->input('id'));
		}
		return $this->renderJson(['list' => $um->paginate(request('limit', 10))]);
	}

	//删除用户发送消息
	public function delUserMsg(Request $request)
	{
		$this->validate($request, [
			'from_user_id' => 'required',
		], [
			'from_user_id.required' => 'from_user_id不能为空',
		]);
		$del = UserMsg::where('to_user_id', '=', $this->user->id)
			->where('from_user_id', $request->input('from_user_id'))->delete();

		return $del ? $this->success() : $this->fail("删除失败");
	}

	//删除脉宝消息
	public function delSysMsg()
	{
		$del = SystemMsg::where('to_user_id', '=', $this->user->id)->delete();

		return $del ? $this->success() : $this->fail("删除失败");
	}
}
